package collector.parsers;

import java.util.HashMap;
import java.util.Iterator;
import java.util.concurrent.Semaphore;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import collector.support.URLHandler;

public class StockFinder extends Thread implements
		Iterable<HashMap<String, String>> {
	private URLHandler urlHandler;
	private HashMap<String, HashMap<String, String>> matches;
	private Semaphore parsing;
	private String market;
	private String list;
	private String url;

	private void init(String market, String list, String delimiters) {
		parsing = new Semaphore(1);

		// Cannada fix, needs to be logged in
		if (market.equals("CA")) {
			matches = new HashMap<String, HashMap<String, String>>();
			return;
		}

		// Go on...
		try {
			parsing.acquire();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		this.market = market;
		this.list = list;
		this.url = "https://www.avanza.se/aza/aktieroptioner/kurslistor/kurslistor.jsp?cc="
				+ market + "&lkey=" + list;
		if (!delimiters.equals(""))
			this.url += "&delimiters="+delimiters;
		this.start();
	}
	
	public StockFinder(String market, String list, String delimiters) {
		init(market, list, delimiters);
	}
	
	public StockFinder(String market, String list) {
		init(market, list, "");
	}

	public void run() {
		urlHandler = URLHandler.create(url);
		matches = new HashMap<String, HashMap<String, String>>();
		String content = urlHandler.getContent();
		content = content.replace(",", "."); // Comma separated numbers will be
		// dot separated insted

		// System.out.println("content:"+content);
		Pattern tablePattern = Pattern
				.compile(
						"<table class ?=\"shareTable\".*?>(.*?<tr.*?>([^<]*)</tr>.*?)?</table>",
						Pattern.CASE_INSENSITIVE);
		Matcher tableMatcher = tablePattern.matcher(content);
		String tdString = null;
		try {
			if (!tableMatcher.find()) {
				System.out.println(tdString);
				System.out.println("No table found!");
				parsing.release();
				return;
			}
			
			tdString = tableMatcher.group(1).trim();

			Pattern tdPattern = Pattern.compile(
					"<tr.*?>((.*?<td.*?>([^<]*)</td>.*?)?)</tr>",
					Pattern.CASE_INSENSITIVE);
			Matcher tdMatcher = tdPattern.matcher(tdString);
			String cellString = null;
			while (tdMatcher.find()) {
				try {
					cellString = tdMatcher.group(1).trim();
					// System.out.println(" cellString: " + cellString);

					Pattern cellPattern = Pattern.compile("<td.*?>(.*?)</td>",
							Pattern.CASE_INSENSITIVE);
					Matcher cellMatcher = cellPattern.matcher(cellString);

					cellMatcher.find();
					cellMatcher.find();
					cellMatcher.find();
					String nameCell = cellMatcher.group(1).trim();
					// System.out.println("nameCell:"+nameCell);
					
					if (nameCell.equals("+/-"))
						continue;
					
					// name and url cell
					HashMap<String, String> match = new HashMap<String, String>();
					Pattern namePattern = Pattern.compile(
							"<a href=\"([^\"]*)\".*?>(.*)</a>",
							Pattern.CASE_INSENSITIVE);
					Matcher nameMatcher = namePattern.matcher(nameCell);
					nameMatcher.find();
					String url = nameMatcher.group(1).trim();
					match.put("url", url);
					// System.out.println("url:" + url);
					String name = nameMatcher.group(2).trim();
					match.put("name", name);
					// System.out.println("name:" + name);

					// change
					cellMatcher.find();
					match.put("change", cellMatcher.group(1));
					// System.out.println("change:" + match.get("change"));

					// changeProc
					cellMatcher.find();
					match.put("changeProc", cellMatcher.group(1));
					// System.out.println("changeProc:" +
					// match.get("changeProc"));

					if (!market.equals("US")) {
						cellMatcher.find();
						cellMatcher.find();
					}

					// last
					cellMatcher.find();
					match.put("value", cellMatcher.group(1));
					// System.out.println("value:" + match.get("value"));

					// high
					cellMatcher.find();
					match.put("high", cellMatcher.group(1));
					// System.out.println("high:" + match.get("high"));

					// low
					cellMatcher.find();
					match.put("low", cellMatcher.group(1));
					// System.out.println("low:" + match.get("low"));

					cellMatcher.find();

					// last
					cellMatcher.find();
					match.put("time", cellMatcher.group(1));
					// System.out.println("time:" + match.get("time"));

					// Find currency
					// <td class="greydarkplain"><b
					// class="greymiddlebold">Handlas
					// i:</b> SEK</td>
					urlHandler = URLHandler.create(match.get("url"));
					String urlContent = urlHandler.getContent();

					Pattern currencyPattern = Pattern
							.compile(
									"<b class=\"greymiddlebold\">Handlas i:</b> ([^<]*)",
									Pattern.CASE_INSENSITIVE);
					Matcher currencyMatcher = currencyPattern
							.matcher(urlContent);
					String currencyString = null;
					try {
						if (currencyMatcher.find()) {
							currencyString = currencyMatcher.group(1).trim();
							// System.out.println(currencyString);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
					match.put("currency", currencyString);
					
					//Kortnamn
					Pattern shortPattern = Pattern
							.compile(
									"<b class=\"greymiddlebold\">Kortnamn:</b> ([^<]*)",
									Pattern.CASE_INSENSITIVE);
					Matcher shortMatcher = shortPattern
							.matcher(urlContent);
					String shortString = null;
					try {
						if (shortMatcher.find()) {
							shortString = shortMatcher.group(1).trim();
							//System.out.println(shortString);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
					match.put("shortname", shortString);

					// all set!
					matches.put(name, match);
				} catch (Exception e) {
					//e.printStackTrace();
				}
			}
		} catch (Exception e) {
			System.err.println("url: " + tdString);
			System.err.println("content: " + content);
			System.err.println("tdString: " + tdString);
			e.printStackTrace();
			System.exit(0);
		}

		parsing.release();
	}

	public HashMap<String, HashMap<String, String>> getStocks() {
		try {
			parsing.acquire();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		HashMap<String, HashMap<String, String>> result = matches;
		parsing.release();
		return result;
	}

	@Override
	public Iterator<HashMap<String, String>> iterator() {
		return getStocks().values().iterator();
	}
}
